package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @Author Pan_Rundong
 * @Date 2023-01-31 10:28
 * @Desc 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Value("${reggie.successUrl}")
    private String successUrl;
    @Value("${reggie.loginUrl}")
    private String loginUrl;

    /**
     *
     * @Autoer Pan Rundong
     * @Date 2023-02-01 8:52
     *   (○` 3′○)~~♡   (°ー°〃)
     * @param user
     * @param session
     * @return com.itheima.reggie.common.R<java.lang.String>
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        log.info("用户手机号为：{}",user.getPhone());
        //获取手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的6位验证码
            String verifyCode = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("code = {}",verifyCode);

            //调用阿里云API
//            SMSUtils.sendMessage("瑞吉外卖","SMS_268475920",phone,verifyCode);

            //将验证码存入Session
            session.setAttribute(phone,verifyCode);
            return R.success("手机验证码短信发送成功");
        }

        return R.error("短信发送失败");
    }

    /**
     * 手机端登录
     * @Autoer Pan Rundong
     * @Date 2023-01-31 15:48
     *   (○` 3′○)~~♡   (°ー°〃)
     * @param map
     * @param session
     * @return com.itheima.reggie.common.R<com.itheima.reggie.entity.User>
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session, HttpServletResponse response){
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从Session中获取保存的验证码
        String verifyCode = session.getAttribute(phone).toString();

        //进行验证码比对
        if (verifyCode != null && verifyCode.equals(code)){
            //如果比对成功，则成功登录
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            if(user == null){
                //判断当前手机号用户是否为新用户，是则保存用户手机号
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
//            response.addCookie(new Cookie("user",user.getId().toString()));
            return R.success(user);
        }
        return R.error("登录失败");
    }

    /**
     * 退出登录
     * @Author: Pan Rundong
     * @Date: 2023-02-06 9:29
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param session
     * @return com.itheima.reggie.common.R<java.lang.String>
     */
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出登录成功");
    }

    @GetMapping("/userPage")
    public void getCookies(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if ("user".equals(name)) {
                String value = cookie.getValue();
                log.info("获取用户Id：{}", value);
                request.getSession().setAttribute("user", Long.parseLong(value));
                response.sendRedirect(successUrl);
            }
        }
        response.sendRedirect(loginUrl);
    }

}
